package leetcode.editor.cn;


public class P371SumOfTwoIntegers {
    public static void main(String[] args) {
        Solution solution = new P371SumOfTwoIntegers().new Solution();
        System.out.println(solution.getSum(20, 30));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int getSum(int a, int b) {
            String s = Integer.toBinaryString(a);
            String t = Integer.toBinaryString(b);
            char[] arr1 = s.toCharArray();
            char[] arr2 = t.toCharArray();
            char[] temp;
            if (arr1.length < arr2.length) {
                temp = arr1;
                arr1 = arr2;
                arr2 = temp;
            }
            int index = arr1.length - 1;
            int index2 = arr2.length - 1;
            char one = '1', zero = '0';
            StringBuilder stringBuilder = new StringBuilder();
            int add = 0;
            while (index >= 0 && index2 >= 0) {
                char c = arr1[index];
                char c1 = arr2[index2];
                if (add == 0) {
                    if ((c == one && c1 != one) || (c1 == one && c != one)) {
                        stringBuilder.append(one);
                    } else if (c == one && c1 == one) {
                        stringBuilder.append(zero);
                        add = 1;
                    }else{
                        stringBuilder.append(zero);
                    }
                }else{
                    if ((c == one && c1 != one) || (c1 == one && c != one)) {
                        stringBuilder.append(zero);
                        add = 1;
                    } else if (c == one && c1 == one) {
                        stringBuilder.append(one);
                        add = 1;
                    }else{
                        stringBuilder.append(one);
                        add = 0;
                    }
                }

                index--;
                index2--;
            }
            while (index >= 0) {
                if (add == 0) {
                    stringBuilder.append(arr1[index]);
                }else{
                    if (arr1[index] == one) {
                        add = 1;
                        stringBuilder.append(zero);
                    }else{
                        add = 0;
                        stringBuilder.append(one);
                    }
                }
                index--;
            }
            if (add == 1) {
                stringBuilder.append(one);
            }
            char[] chars = stringBuilder.toString().toCharArray();
            int sum = 0;
            for (int i = chars.length-1; i >=0; i--) {
                sum = sum * 2 + (chars[i] == one ? 1 : 0);
            }
            return sum;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}